package com.itany.mall.service.impl;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itany.mall.dao.OrderDao;
import com.itany.mall.dao.OrderDetailDao;
import com.itany.mall.entity.Order;
import com.itany.mall.entity.OrderDetail;
import com.itany.mall.entity.User;
import com.itany.mall.exception.OrderNotFoundException;
import com.itany.mall.factory.Autowired;
import com.itany.mall.factory.Component;
import com.itany.mall.service.OrderService;

@Component
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private OrderDetailDao orderDetailDao;

	@Override
	public void commitOrder(Collection<OrderDetail> shopingCart) {

		User u = null;
		double price = 0D;
		for (OrderDetail od : shopingCart) {
			u = od.getUser();
			price += od.getPrice();
		}

		// 确认下单, 会产生一个订单对象
		Order order = new Order();
		order.setUser(u);
		order.setOrderNum(new Date().getTime() + "");
		order.setCreateTime(new Date());
		order.setPrice(price);

		// 将订单对象保存, 获得保存数据是产生的id值
		long id = orderDao.insert(order);
		order.setId(id);

		// 将该订单与各订单详情绑定, 并将各详情保存(或更新)
		for (OrderDetail od : shopingCart) {
			od.setOrder(order);
		}

		orderDetailDao.saveOrUpdateOrderDetails(shopingCart);

	}

	@Override
	public List<Order> findMyOrders(long userId) {
		return orderDao.selectByUserId(userId);
	}

	@Override
	public Map<Order, List<OrderDetail>> findDetailsByOrderNum(String num, long userId)
			throws OrderNotFoundException {
		Order o = orderDao.selectByNumAndUserId(num, userId);
		if (o == null) {
			throw new OrderNotFoundException();
		}

		List<OrderDetail> list = orderDetailDao.selectByOrderNum(num);

		return new HashMap<Order, List<OrderDetail>>() {
			{
				put(o, list);
			}
		};
	}

}
